<template>
  <transition name="bounce" mode="out-in">
    <div class="mui-content mh-containe pd">
      <mh-header :headName="chatName" :showSetting="showSetting" @setting="chatSetting" ref="mhHead"> </mh-header>
      <div class="msg-content" :style="{height:styles.contentView+'px'}">
        <div class="m-item" v-for="(message,index) in messages" :key="index">
          <div class="m-left">
            <img class="head_icon" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3879024388,2425631276&fm=26&gp=0.jpg" v-if="message.user === 'home'">
          </div>
          <div class="m-content" :class="{rt: message.user === 'customer'}">
            <div class="m-content-head" :class="{'m-content-head-right':message.user === 'customer'}">
              <div :class="'m-content-head-'+message.user">{{message.content}} </div>
            </div>
          </div>
          <div class="m-right">
            <img class="head_icon" src="http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJKpp1HCnDWb1TI4zG7mvIYoHjotHJGdTM7dpkACGfueIfQYIBvnCFHQqLca7l3HFHUQCbNARGqdA/132" v-if="message.user === 'customer'">
          </div>
        </div>
      </div>
      <mh-chat ref="chatFoot" @recalHeight="recalHeight"> </mh-chat>
    </div>
  </transition>
</template>

<script>
  import MhHeader from '@/components/mh-header/mh-header'
  import MhChat from '@/components/mh-chat/chat-footer'
  import {MH_API} from "@/api/api";
  export default {
    name: "msg-chat",
    data () {
      return {
        chatName: '聊天',
        showSetting: true,
        styles: {
          head: 90,
          contentView: 0,
          foot: 188
        },
        messages: [
          // {
          //   user: 'home',
          //   type: 'head', //input,content
          //   content: '123'
          // },
        ],
        targetId: 1000,
        userId: null,
        id: null,
        dangeArr: []
      }
    },
    mounted () {
      this.styles.foot = this.$refs['chatFoot'].$el.offsetHeight;
      this.styles.head = this.$refs['mhHead'].$el.offsetHeight;
      this.styles.contentView = document.body.clientHeight - this.styles.head - this.styles.foot;

      let self= this;
      let rongyun = JSON.parse(window.localStorage.getItem("rongyun"));
      console.log(rongyun)
      let token = rongyun.token;
      let userId = rongyun.id;
      this.userId = userId;
      
      RongIMLib.RongIMClient.init("sfci50a7s3qxi");
      // 设置连接监听状态 （ status 标识当前连接状态 ）
       // 连接状态监听器
       RongIMClient.setConnectionStatusListener({
          onChanged: function (status) {
              switch (status) {
                  case RongIMLib.ConnectionStatus.CONNECTED:
                      console.log('链接成功');
                      break;
                  case RongIMLib.ConnectionStatus.CONNECTING:
                      console.log('正在链接');
                      break;
                  case RongIMLib.ConnectionStatus.DISCONNECTED:
                      console.log('断开连接');
                      break;
                  case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                      console.log('其他设备登录');
                      break;
                    case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                      console.log('域名不正确');
                      break;
                  case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                    console.log('网络不可用');
                    break;
                  }
          }});

       // 消息监听器
       RongIMClient.setOnReceiveMessageListener({
          // 接收到的消息
          onReceived: function (message) {
              console.log(message)
              // 判断消息类型
              switch(message.messageType){
                  case RongIMClient.MessageType.TextMessage:
                      // message.content.content => 消息内容
                      //console.log(message.content.content)
                      if(message.senderUserId != self.targetId){
                        self.messages.push({
                          user: 'home',
                          content: message.content.content
                        })
                      }
                      // if(message.content.content){
                      //     var temp = '<div class="mes-box your"><div class="logo"><img src="'+yourLogo+'"></div><div class="con"><em></em>'+message.content.content+'</div></div>'
                      //     $("#rcs-app").append(temp);
                      // }
                      break;
                  case RongIMClient.MessageType.VoiceMessage:
                      // 对声音进行预加载                
                      // message.content.content 格式为 AMR 格式的 base64 码
                      break;
                  case RongIMClient.MessageType.ImageMessage:
                     // message.content.content => 图片缩略图 base64。
                     // message.content.imageUri => 原图 URL。
                     break;
                  case RongIMClient.MessageType.DiscussionNotificationMessage:
                     // message.content.extension => 讨论组中的人员。
                     break;
                  case RongIMClient.MessageType.LocationMessage:
                     // message.content.latiude => 纬度。
                     // message.content.longitude => 经度。
                     // message.content.content => 位置图片 base64。
                     break;
                  case RongIMClient.MessageType.RichContentMessage:
                     // message.content.content => 文本消息内容。
                     // message.content.imageUri => 图片 base64。
                     // message.content.url => 原图 URL。
                     break;
                  case RongIMClient.MessageType.InformationNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.ContactNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.ProfileNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.CommandNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.CommandMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.UnknownMessage:
                      // do something...
                     break;
                  default:
                      // do something...
              }
          }
      });

      //链接服务器
      RongIMClient.connect(token, {
          onSuccess: function(userId) {
            console.log("Connect successfully." + userId);
          },
          onTokenIncorrect: function() {
            console.log('token无效');
          },
          onError:function(errorCode){
                var info = '';
                switch (errorCode) {
                  case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                  case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                  case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                  case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
                }
                console.log(errorCode);
              }
        });

      //设置重连
      var callback = {
          onSuccess: function(userId) {
              console.log("Reconnect successfully." + userId);
          },
          onTokenIncorrect: function() {
              console.log('token无效');
          },
          onError:function(errorCode){
              console.log(errorcode);
          }
      };
      var config = {
          // 默认 false, true 启用自动重连，启用则为必选参数
          auto: true,
          // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
          url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
          // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
          rate: [100, 1000, 3000, 6000, 10000]
      };
      RongIMClient.reconnect(callback, config);
      setTimeout(function(){
        //self.send();
        // let targetId = 1000;
        //获取历史记录
        var conversationType = RongIMLib.ConversationType.PRIVATE; //单聊,其他会话选择相应的消息类型即可。
        var timestrap = 0; // 默认传 null，若从头开始获取历史消息，请赋值为 0 ,timestrap = 0;
        var count = 10; // 每次获取的历史消息条数，范围 0-20 条，可以多次获取。
        var targetId = self.id + '';
        console.log(targetId)
        RongIMLib.RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, timestrap, count, {
          onSuccess: function(list, hasMsg) {
               // list => Message 数组。
            // hasMsg => 是否还有历史消息可以获取。
            console.log(list)
            let messages = [];
            for(let i=0, len=list.length;i<len;i++){
              let user = 'home';
              if(userId==list[i].senderUserId){
                user = 'customer'
              }
              messages.push({
                user: user,
                type: 'head',
                content: list[i].content.content
              })
            }
            self.messages = messages;
          },
          onError: function(error) {
            console.log("GetHistoryMessages,errorcode:" + error);
          }
        });
      }, 500)
    },
    created () {
      this.chatName = this.$route.query.name;
      this.id = this.$route.query.id;
      this.targetId = window.localStorage.getItem("userid");
      console.log(this.targetId)
      this.getDange();
    },
    methods: {
      getDange(){
        let self = this;
        MH_API.getSensitive({

        }).then(res => {
          if (res.status == 200) {
            self.dangeArr = res.data;
          }
        })
      },
      recalHeight (footHeight) {
        this.styles.foot = footHeight;
        console.log(footHeight);
        this.styles.contentView = document.body.clientHeight - this.styles.head - this.styles.foot;
      },
      chatSetting () {
        this.$router.push({
          path: '/chat/setting'
        })
      },
      //发送文本消息
      send(mesVal){
          //var mesVal = $("#mes1").val();
          let self = this;
          //var mesVal = '测试发送消息';
          if(!mesVal){
              return false
          }
          if(self.dangeArr.length > 0){
            for(let i=0,len=self.dangeArr.length;i<len;i++){
              console.log(mesVal.indexOf(self.dangeArr[i]))
              if(mesVal.indexOf(self.dangeArr[i]) != "-1"){
                mui.toast("内容有敏感词")
                return false
              }
            }
          }
          var msg = new RongIMLib.TextMessage({content:mesVal,extra:"附加信息"});
          var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
          RongIMClient.getInstance().sendMessage(conversationtype, self.targetId, msg, {
                      onSuccess: function (message) {
                          //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                          console.log("Send successfully");
                          console.log(message);
                          self.messages.push({
                            user: 'customer',
                            content: mesVal
                          })
                          self.$refs.chatFoot.clearMsg();
                          // var temp = '<div class="mes-box mine"><div class="con"><em></em>'+mesVal+'</div><div class="logo"><img src="'+avatar+'"></div></div>'
                          // $("#rcs-app").append(temp);
                          // $("#mes1").val("");
                      },
                      onError: function (errorCode,message) {
                          var info = '';
                          switch (errorCode) {
                              case RongIMLib.ErrorCode.TIMEOUT:
                                  info = '超时';
                                  break;
                              case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                  info = '未知错误';
                                  break;
                              case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                                  info = '在黑名单中，无法向对方发送消息';
                                  break;
                              case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                                  info = '不在讨论组中';
                                  break;
                              case RongIMLib.ErrorCode.NOT_IN_GROUP:
                                  info = '不在群组中';
                                  break;
                              case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                                  info = '不在聊天室中';
                                  break;
                              default :
                                  info = x;
                                  break;
                          }
                          console.log('发送失败:' + info);
                      }
                  }
              );
      }
    },
    components: {
      MhHeader,
      MhChat
    }
  }
</script>

<style lang="scss" scoped>
  .m-item {
    display: flex;
    flex-direction: row;
    padding-top: 2rem;
  }
  .m-left {
    display: flex;
    width: 6rem;
    justify-content: center;
    align-items: flex-start;
  }
  .m-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    word-break: break-all;
    &.rt {flex: 1;}
  }
  .m-right {
    display: flex;
    width: 6rem;
    justify-content: center;
    align-items: flex-start;
  }
  .head_icon {
    width: 4rem;
    height: 4rem;
    border-radius: 100%;
  }
  .m-content-head {
    position: relative;
  }
  .m-content-head-right {
    display: flex;
    justify-content: flex-end;
  }
  .m-content-head-home {
    text-align: left;
    background: linear-gradient(180deg,#dd65a1 30%, #fa625a 100%);
    border-radius: 1rem;
    padding: 1rem;
    color: white;
  }
  .m-content-head-home:before {
    border: .75rem solid transparent;
    border-right: .75rem solid #dd65a1;
    left: -1.3rem;
    width: 0;
    height: 0;
    position: absolute;
    content: ' '
  }
  .m-content-head-customer {
    border: 1px white solid;
    background: white;
    border-radius: 1rem;
    padding: 1rem;
  }
  .m-content-head-customer:after {
    border: .75rem solid transparent;
    border-left: .75rem solid white;
    top: 1rem;
    right: -1.3rem;
    width: 0;
    height: 0;
    position: absolute;
    content: ' '
  }
</style>
